const express = require('express')
const dotenv = require('dotenv')
const cors = require('cors')
const { formatDate } = require('ts-fns')
const formidable = require('formidable')
const { createRequest, createSDK, containsContentType } = require('./index')

dotenv.config()

const {
  HOST = '127.0.0.1',
  PORT = 9000,
  REQUEST_URI = '/request',
  MOCK_URI = '/mock',
  SDK_URI = '/sdk.js',
} = process.env

const app = express()
app.use(express.text())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(cors())

app.post(REQUEST_URI, createRequest('run'))
app.post(MOCK_URI, createRequest('mock'))
app.get(SDK_URI, createSDK())

app.get('/test', (req, res) => {
  res.send('ok')
})

// 开发测试用
if (process.env.NODE_ENV === 'development') {
  app.post('/api', (req, res) => {
    if (containsContentType(req, 'text/plain')) {
      console.log('text:', req.body)
      res.send(req.body)
      return
    }

    if (containsContentType(req, 'application/json') || containsContentType(req, 'application/x-www-form-urlencoded')) {
      console.log('json:', req.body)
      res.json({
        name: 'tom',
        age: 10,
        id: 1,
        ...req.body,
      })
      return
    }

    if (containsContentType(req, 'multipart/form-data')) {
      const form = formidable({ multiples: true })
      form.parse(req, (err, fields, files) => {
        console.log('files:', fields, files)
        res.json({
          fields,
          files,
          id: 1,
          name: 'tom',
          age: 10,
        })
      })
      return
    }

    res.status(500)
    res.send({ code: 500, message: '不支持接收的文档类型' })
    console.error(formatDate('YYYY-MM-DD HH:mm:ss'), '不支持接收的文档类型')
  })
  app.get('/*', express.static(__dirname))
}

app.listen(PORT, HOST)
